﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;


using System.IO;
using System.Xml;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Net;




namespace UpdateClient {
	public partial class Form1 : Form {
		[DllImport("kernel32")]
		public static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);  //获取ini文件中的数据
		[DllImport("kernel32")]
		public static extern long WritePrivateProfileString(string section, string key, string val, string filePath);  //写入ini文件数据

		public string CurrentVerXMLPath;
		public string UpdateVerXMLPath;
		public Form1() {
			InitializeComponent();

			this.UpdateVersionLbl.Text = this.UpdateTimeLbl.Text = this.UpdateInfoTxt.Text = "  正在加载中...";
			this.StartUpdateBtn.Enabled = false;
			LoadCurrentVersion();
			//Thread th = new Thread(new ThreadStart(LoadUpdateVersion));
			//th.Start();
			LoadUpdateVersion();
		}

		private void LoadCurrentVersion() {
			string AppPath = Application.StartupPath;
			CurrentVerXMLPath = AppPath + "\\info\\UpdateInfo.xml";
			XmlDocument doc = new XmlDocument();
			try {
				doc.Load(CurrentVerXMLPath);
				this.CurrentTimeLbl.Text = doc.GetElementsByTagName("UpdateTime")[0].Attributes[0].Value;
				//this.CurrentTimeLbl.Text = doc.GetElementsByTagName("UpdateUser")[0].Attributes[0].Value;
				this.CurrentVersionLbl.Text = doc.GetElementsByTagName("UpdateVersion")[0].Attributes[0].Value;
				this.CurrentUpdateInfoTxt.Text = doc.GetElementsByTagName("UpdateText")[0].InnerText;

			} catch {
				this.CurrentTimeLbl.Text = "2014-09-24 00:00:00";
				this.CurrentVersionLbl.Text = "2.0.0.0";
			}
		}

		private void LoadUpdateVersion() {
			string UpdatePath = $"http://61.162.59.62:7999/Update/Client";
			UpdateVerXMLPath = UpdatePath + "/UpdateInfo.xml";
			var doc = new XmlDocument();
			try {
				var wr = WebRequest.Create(UpdateVerXMLPath) as HttpWebRequest;
				var wrs = (HttpWebResponse)wr.GetResponse();
				var ss = wrs.GetResponseStream();
				doc.Load(ss);
				this.UpdateTimeLbl.Text = doc.GetElementsByTagName("UpdateTime")[0].Attributes[0].Value;
				//this.CurrentTimeLbl.Text = doc.GetElementsByTagName("UpdateUser")[0].Attributes[0].Value;
				this.UpdateVersionLbl.Text = doc.GetElementsByTagName("UpdateVersion")[0].Attributes[0].Value;
				this.UpdateInfoTxt.Text = doc.GetElementsByTagName("UpdateText")[0].InnerText;
				if (this.CurrentVersionLbl.Text == this.UpdateVersionLbl.Text) {
					this.StartUpdateBtn.Enabled = false;
					return;
				}
			} catch {
				this.UpdateTimeLbl.Text = "加载错误";
				this.UpdateVersionLbl.Text = "加载错误";
				this.UpdateInfoTxt.Text = "加载错误";
			}
			this.StartUpdateBtn.Enabled = true;
		}

		private void StartUpdateBtn_Click(object sender, EventArgs e) {

			if (DialogResult.Yes == MessageBox.Show("更新会重启系统，是否更新？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question)) {
				try {
					if (Process.GetProcessesByName("client").Length > 0)
						Process.GetProcessesByName("client")[0].Kill();
				} catch (Exception ex) {
					MessageBox.Show("客户端关闭失败:" + ex.Message);
				}
				Thread.Sleep(2000);
				try {

					//Directory.GetFiles(String, String)方法
					//第一个string：要搜索的目录。
					//第二个string：要与"目录"中的文件名匹配的搜索字符串。
					//搜索是否存在 UpdateInfo 文件  存在就更新  不存在就不更新
					XmlDocument doc = new XmlDocument();
					HttpWebRequest wr = (HttpWebRequest)HttpWebRequest.Create(UpdateVerXMLPath);
					HttpWebResponse wrs = (HttpWebResponse)wr.GetResponse();
					Stream ss = wrs.GetResponseStream();
					doc.Load(ss);
					XmlNodeList cml = doc.GetElementsByTagName("File");
					foreach (XmlNode xn in cml) {
						string FileName = xn.InnerText;
						string FilePath = Application.StartupPath + "\\" + FileName;
						if (File.Exists(FilePath)) {
							if (File.Exists(Path.GetFileNameWithoutExtension(FilePath) + "_bak." + Path.GetExtension(FilePath).Replace(".", ""))) {
								File.Delete(Path.GetFileNameWithoutExtension(FilePath) + "_bak." + Path.GetExtension(FilePath).Replace(".", ""));
							}
							File.Copy(FilePath, Path.GetFileNameWithoutExtension(FilePath) + "_bak." + Path.GetExtension(FilePath).Replace(".", ""), true);
							File.Delete(FilePath);
						}
						label5.Text = "正在下载:" + FileName;
						DownloadFile(UpdateVerXMLPath.Replace("UpdateInfo.xml", "") + FileName, FilePath, prog);
					}
					string UpdateFile = Application.StartupPath + "\\UpdateInfo.xml";
					if (File.Exists(UpdateFile)) {
						if (File.Exists(Path.GetFileNameWithoutExtension(UpdateFile) + "_bak." + Path.GetExtension(UpdateFile).Replace(".", ""))) {
							File.Delete(Path.GetFileNameWithoutExtension(UpdateFile) + "_bak." + Path.GetExtension(UpdateFile).Replace(".", ""));
						}
						File.Copy(UpdateFile, Path.GetFileNameWithoutExtension(UpdateFile) + "_bak." + Path.GetExtension(UpdateFile).Replace(".", ""), true);//客户端下   如果已经存在 CallCenterClient_bak.exe文件  就将其删除
						File.Delete(UpdateFile);
					}
					label5.Text = "正在下载:" + Path.GetFileName(UpdateFile);
					DownloadFile(UpdateVerXMLPath, UpdateFile, prog);
					label5.Text = "更新完成";
					this.StartUpdateBtn.Enabled = false;
				} catch (Exception ex) {
					label5.Text = "更新失败：" + ex.Message;
				}
			}
		}


		public void DownloadFile(string URL, string filename, System.Windows.Forms.ProgressBar prog) {
			try {
				System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
				System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
				long totalBytes = myrp.ContentLength;
				if (prog != null) {
					prog.Maximum = (int)totalBytes;
				}
				System.IO.Stream st = myrp.GetResponseStream();
				System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.OpenOrCreate);
				long totalDownloadedByte = 0;
				byte[] by = new byte[1024];
				int osize = st.Read(by, 0, (int)by.Length);
				while (osize > 0) {
					totalDownloadedByte = osize + totalDownloadedByte;
					System.Windows.Forms.Application.DoEvents();
					so.Write(by, 0, osize);
					if (prog != null) {
						prog.Value = (int)totalDownloadedByte;
					}
					osize = st.Read(by, 0, (int)by.Length);
				}
				so.Close();
				st.Close();
			} catch (System.Exception ex) {
				throw;
			}
		}

		private void LastUpdateBtn_Click(object sender, EventArgs e) {
			//回滚更新  （若更新失败，就更新到以前版本）   只有当文件夹下存在  CallCenterClient_bak.exe 才可以回滚
			//将 客户端的 CallCenterClient_bak.exe 还原为 CallCenterClient.exe
			if (DialogResult.Yes == MessageBox.Show("更新会重启系统，是否更新？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question)) {
				try {
					if (Process.GetProcessesByName("CallCenterClient").Length > 0)
						Process.GetProcessesByName("CallCenterClient")[0].Kill();
				} catch (Exception ex) {
					MessageBox.Show("客户端关闭失败:" + ex.Message);
				}
				Thread.Sleep(1000);
				if (File.Exists(Application.StartupPath + "\\UpdateInfo_bak.xml") && File.Exists(Application.StartupPath + "\\UpdateInfo.xml")) {
					try {
						XmlDocument doc = new XmlDocument();
						doc.Load("UpdateInfo.xml");
						XmlNodeList cml = doc.GetElementsByTagName("File");
						foreach (XmlNode xn in cml) {
							string FileName = xn.InnerText;
							string FilePath = Application.StartupPath + "\\" + FileName;
							if (File.Exists(FilePath)) {
								File.Delete(FilePath);
								File.Copy(Path.GetFileNameWithoutExtension(FilePath) + "_bak." + Path.GetExtension(FilePath).Replace(".", ""), FilePath, true);//客户端下   如果已经存在 CallCenterClient_bak.exe文件  就将其删除
								File.Delete(Path.GetFileNameWithoutExtension(FilePath) + "_bak." + Path.GetExtension(FilePath).Replace(".", ""));
							}
							label5.Text = "正在回滚安装:" + FileName;
						}

						label5.Text = "正在回滚安装:" + Application.StartupPath + "\\UpdateInfo.xml";
						File.Delete(Application.StartupPath + "\\UpdateInfo.xml");
						File.Copy(Path.GetFileNameWithoutExtension(Application.StartupPath + "\\UpdateInfo.xml") + "_bak.xml", Application.StartupPath + "\\UpdateInfo.xml", true);//客户端下   如果已经存在 CallCenterClient_bak.exe文件  就将其删除
						File.Delete(Path.GetFileNameWithoutExtension(Application.StartupPath + "\\UpdateInfo.xml") + "_bak.xml");
						label5.Text = "回滚安装成功";
						this.StartUpdateBtn.Enabled = true;
					} catch (Exception ex) {
						label5.Text = "回滚安装失败：" + ex.Message;
						MessageBox.Show("回滚安装失败：" + ex.Message);
					}
				} else {
					MessageBox.Show("系统没有更新，无法回滚！");
				}
			}
		}

		private void CloseBtn_Click(object sender, EventArgs e) {
			this.Close();
		}

		private void Form1_Load(object sender, EventArgs e) {
			//获取屏幕分辨率
			int Swidth = Screen.PrimaryScreen.Bounds.Width;
			int Sheight = Screen.PrimaryScreen.Bounds.Height;
			//获取程序的大小
			int Awidth = this.Width;
			int Aheight = this.Height;
			//加载程序时使程序居中
			this.Left = Swidth / 2 - Awidth / 2;
			this.Top = Sheight / 2 - Aheight / 2 - 50;
		}
	}
}
